package com

import (
	"errors"
	"odm/logger"

	"github.com/kataras/iris/v12"
)

// Authorize middleware
func Authorize() iris.Handler {
	return func(ctx iris.Context) {
		token := ctx.Request().Header.Get("Authorization")
		if token == "" || token == "null" {
			logger.Error("上传的令牌为空")
			ctx.StopWithError(iris.StatusUnauthorized, errors.New("上传的令牌为空"))
			return
		}
		username, err := VerifyToken(token)
		if err != nil {
			ctx.StopWithError(iris.StatusUnauthorized, err)
			return
		}
		ctx.Values().Set("username", username)
		logger.Debugf("Token authorize success [username=%s token=%s]", username, token)
		ctx.Next()
	}
}

// Middleware 中间件
func Middleware() iris.Handler {
	return func(ctx iris.Context) {
		// 日志打印
		method := ctx.Request().Method
		uri := ctx.Request().RequestURI
		remote := ctx.RemoteAddr()
		logger.Logf("%s %s %s", remote, method, uri)
		ctx.Next()
		status := ctx.GetStatusCode()
		logger.Logf("%s %s %s %d", remote, method, uri, status)
	}
}
